package com.plugin.gocqhttp.event;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import com.plugin.gocqhttp.pojo.annotation.RequireValue;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

/**
 * 通用接口
 * @param <T>
 */
@Slf4j
public  abstract  class AbstractEventTypeSupperGenerics<T> implements EventTypeHandler,EventTypeAdaptHandler<T>  {

    public abstract Class getEntityClass();

    public T object;

    @Override
    public boolean suppert(JSONObject requestParam) {
        T parseObj = getParseObj(requestParam);
        this.object = parseObj;
        if (null == parseObj) { return false;}
        if (!checkRequiredAnnotion()) {return false;}
        return true;
    }

    @Override
    public Object handlerRequest(JSONObject requestParam) {
        return work(requestParam,object);
    }


    /**
     * ADD RequireValue check
     * @return
     */
    private boolean checkRequiredAnnotion() {
        Class entityClass = getEntityClass();
        Field[] fields =entityClass.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            RequireValue annotation = field.getAnnotation(RequireValue.class);
            if (null == annotation){continue;}
            try {
                if (null == field.get(object)){
                    return false;
                }
                String fileValue = field.get(object).toString();
                //只要包含有一个注解里面属性
                if (annotation.logic() == 1){
                    boolean logicCheck=false;
                    for (String s : annotation.value()) {
                        if (s.equals(fileValue)){
                            logicCheck=true;
                        }
                    }
                    return logicCheck;
                }
                // 必须包含属性
                String annotationValue = annotation.value()[0];
                if (!annotationValue.equals(fileValue)){return false;}
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return true;
    }



    public T getParseObj(JSONObject requestParam){
        try {
            return  (T) JSON.toJavaObject(requestParam, getEntityClass());
        } catch (Exception e) {
            return null;
        }
    }


}
